<%@ page pageEncoding="UTF-8"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<html lang="zh">
<head>
<%@ include file="/include/header_base.jsp"%>
<%@ include file="/include/header_easyui.jsp"%>
<%@ include file="/include/header_other.jsp"%>
<%@ include file="/include/taglib.jsp"%>
</head>
<body>
	<div class="layui-container" style="margin-top: 15px;">
		<div class="layui-row">
			<form id="assignPermissionForm" class="layui-form">
				<input type="hidden" id="roleId" value="${roleId}"/>
				<div class="layui-form-item">
					<ul id="permissionTree" class="easyui-tree">
					</ul>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn layui-btn-sm" lay-submit>保存</button>
						<button id="cancelAssignPermissionBtn"
							class="layui-btn layui-btn-sm">取消</button>
					</div>
				</div>
			</form>
		</div>
	</div>

	<script type="text/javascript">
		$(function() {
			$('#permissionTree').tree({
				url : '${ctx}/permission/initPermissionTreeTable',
				lines : true,
				checkbox : true,
				cascadeCheck : false, // 不设置级联检查
				onLoadSuccess : function(node, data) {
					<c:forEach items="${perms}" var="perm">
					// 获取权限ID
					var id = '${perm.id}'
					// 根据id找节点
					var node = $("#permissionTree").tree("find", id);
					// 设置节点选中
					$("#permissionTree").tree("check", node.target);
					</c:forEach>
				}
			});

			$('#cancelAssignPermissionBtn').click(function() {
				closeDialog();
			})

			$('#assignPermissionForm').on('submit', function() {
				var nodes = $('#permissionTree').tree('getChecked');
				if (!nodes || nodes.length == 0) {
					layer.msg("至少选择一条记录");
					return;
				}
				
				var roleId = $('#roleId').val();
				var ids = [];
				
				for (var i = 0; i < nodes.length; i++) {
					ids.push(nodes[i].id);
				}

				$(this).ajaxSubmit({
					type : "post",
					url : "${ctx}/permission/assignPermissions",
					async : false,
					dataType : "json",
					data : {
						roleId : roleId,
						ids : ids
					},
					cache : false,
					success : function(data) {
						if (data.code == 0) {
							operSuccess();
						} else {
							operFail();
						}
					},
					error : function(data) {
						operFail();
					}
				})
				return false;
			})
		})
	</script>
</body>
</html>
